package top.ashman.demo.springcloud.eurekaclient;

import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuples;

import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author sunzhaojie
 * @date 2018-12-05
 */
@RestController
@RequestMapping("/my")
public class MyController {

    @GetMapping("/hello")
    public Mono<String> hello() {
        return Mono.just("Hello World, Thread Name: " + Thread.currentThread().getName());
    }

    @GetMapping("/sleep/{seconds}")
    public Mono<String> sleepAndHello(@PathVariable Long seconds) throws InterruptedException {
        if (seconds == null || seconds <= 0) {
            seconds = 1L;
        }

        // noinspection BlockingMethodInNonBlockingContext
        TimeUnit.SECONDS.sleep(seconds);
        return Mono.just("Hello World, Thread Name: " + Thread.currentThread().getName());
    }

    /**
     * Server-Sent Events
     *
     * @param seconds Duration
     * @return Random
     */
    @GetMapping("/random")
    public Flux<ServerSentEvent<Integer>> randomNumber(@RequestParam Long seconds) {
        return Flux.interval(Duration.ofSeconds(seconds))
                .map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt()))
                .map(data -> ServerSentEvent.<Integer>builder()
                        .event("random")
                        .id(Long.toString(data.getT1()))
                        .data(data.getT2())
                        .build());
    }
}
